package com.ysd.lis.service.lab.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.entity.*;
import com.ysd.lis.entity.lab.LabItemDict;
import com.ysd.lis.entity.lab.LabRptGroup;
import com.ysd.lis.entity.lab.LabRulesVsItemdict;
import com.ysd.lis.entity.lab.PubPeportRulesExist;
import com.ysd.lis.mapper.lab.LabItemDictMapper;
import com.ysd.lis.mapper.lab.LabRulesVsItemdictMapper;
import com.ysd.lis.mapper.pub.PubReportMapper;
import com.ysd.lis.mapper.pub.PubReportRulesMapper;
import com.ysd.lis.mapper.sys.SysBasDictDetailMapper;
import com.ysd.lis.mapper.sys.SysMenuMapper;
import com.ysd.lis.mapper.sys.SysPointsMapper;
import com.ysd.lis.request.DeleteParam;
import com.ysd.lis.request.LabRulesVsItemdictDto;
import com.ysd.lis.request.ReportRulesPageParam;
import com.ysd.lis.request.lab.ReportRuleDto;
import com.ysd.lis.service.lab.LabRptGroupService;
import com.ysd.lis.service.lab.LabRulesVsItemdictService;
import com.ysd.lis.service.lab.PubPeportRulesExistService;
import com.ysd.lis.service.lab.ReportRulesService;
import com.ysd.util.IncrementalNumberGenerator;
import com.ysd.util.RedisUserManager;
import com.ysd.util.ToolsUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * cold_chain.SYS_REPORT 服务实现类
 * </p>
 *
 * @author Bai
 * @since 2023-11-24
 */
@Service
public class ReportRulesServiceImpl extends ServiceImpl<PubReportRulesMapper, PubReportRules> implements ReportRulesService {
    @Autowired
    PubReportMapper pubReportMapper;
    @Autowired
    PubReportRulesMapper pubReportRulesMapper;
    @Autowired
    SysPointsMapper pointsMapper;
    @Autowired
    SysMenuMapper menuMapper;
    @Autowired
    SysBasDictDetailMapper basDictDetailMapper;
    @Autowired
    LabRptGroupService rptGroupService;
    @Autowired
    LabRulesVsItemdictMapper rulesVsItemdictMapper;
    @Autowired
    LabItemDictMapper itemDictMapper;
    @Autowired
    LabRulesVsItemdictService rulesVsItemdictService;
    @Autowired
    PubPeportRulesExistService rulesExistService;


    public Result getPageList(ReportRulesPageParam reportRulesPageParam) {
        Map<String, Object> returnMap = new HashMap<>();
        LambdaQueryWrapper<PubReportRules> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        Page<PubReportRules> page = new Page<PubReportRules>();
        page.setCurrent(reportRulesPageParam.getPageIndex());
        page.setSize(reportRulesPageParam.getPageSize());
        lambdaQueryWrapper.eq(PubReportRules::getDelFlag, 0);
        SysUser sysUser = RedisUserManager.getUser();
        if (ToolsUtils.isEmpty(reportRulesPageParam.getType())) {
            return Result.fail("获取报告规则列表，务必传入type类型", returnMap);
        }
        if (ToolsUtils.isNotEmpty(sysUser)) {
            lambdaQueryWrapper.eq(PubReportRules::getOrgId, sysUser.getOrgId());
        }
//        if (StringUtils.isNotBlank(reportPageParam.getModuleId())) {
//            lambdaQueryWrapper.eq(PubReport::getModuleId, reportPageParam.getModuleId());
//        }
//        if (StringUtils.isNotBlank(reportPageParam.getMenuId())) {
//            lambdaQueryWrapper.eq(PubReport::getMenuId, reportPageParam.getMenuId());
//        }
//        if (StringUtils.isNotBlank(reportPageParam.getCommonId())) {
//            lambdaQueryWrapper.eq(PubReport::getCommonId, reportPageParam.getCommonId());
//        }
//        if (StringUtils.isNotBlank(reportPageParam.getPointsId())) {
//            lambdaQueryWrapper.eq(PubReport::getPointsId, reportPageParam.getPointsId());
//        }
//        if (StringUtils.isNotBlank(reportPageParam.getKeywords())) {
//            lambdaQueryWrapper.like(PubReport::getName, reportPageParam.getKeywords());
//        }
        lambdaQueryWrapper.eq(PubReportRules::getType, reportRulesPageParam.getType());
        lambdaQueryWrapper.orderByDesc(PubReportRules::getEditTime);
        Page<PubReportRules> rulesPageList = pubReportRulesMapper.selectPage(page, lambdaQueryWrapper);
        List<PubReportRules> listPubReport = rulesPageList.getRecords();
        if (ToolsUtils.isNotEmpty(listPubReport)) {
            for (PubReportRules pubReportRules : listPubReport) {
                if (ToolsUtils.isNotEmpty(pubReportRules.getReportCode())) {
                    List<PubReport> pubReports = pubReportMapper.selectList(new LambdaQueryWrapper<PubReport>().eq(PubReport::getCode, pubReportRules.getReportCode()));
                    pubReportRules.setReportName(CollectionUtil.isNotEmpty(pubReports) ? pubReports.get(0).getName() : "");
                }
//                if(ToolsUtils.isNotEmpty(pubReport.getPointsId())){
//                    SysPoints points =   pointsMapper.selectById(pubReport.getPointsId());
//                    pubReport.setPointsName(points.getTitle());
//                }
//                if(ToolsUtils.isNotEmpty(pubReport.getMenuId())){
//                    SysMenu menu =   menuMapper.selectById(pubReport.getMenuId());
//                    pubReport.setMenuName(menu.getTitle());
//                }
                if (ToolsUtils.isNotEmpty(pubReportRules.getRptGroup())) {
                    LambdaQueryWrapper<SysBasDictDetail> basDictDetailWrapper = new LambdaQueryWrapper<>();
                    basDictDetailWrapper.eq(SysBasDictDetail::getDelFlag, "0").eq(SysBasDictDetail::getCode, "name").eq(SysBasDictDetail::getCommonId, pubReportRules.getRptGroup());
                    List<SysBasDictDetail> basDictDetails = basDictDetailMapper.selectList(basDictDetailWrapper);
                    if (ToolsUtils.isNotEmpty(basDictDetails)) {
                        pubReportRules.setReportGroupName(basDictDetails.get(0).getValue());
                    }
                }
            }
            rulesPageList.setRecords(listPubReport);
            returnMap.put("rulesList", rulesPageList);
        }
        return Result.succ(1, "获取信息成功", returnMap);
    }

    @Override
    public Result getReportAsName() {
        String reportAsName = IncrementalNumberGenerator.generateIncrementalNumber3();
        return Result.succ(reportAsName);
    }

    @Override
    public Result getReportGroupTree(ReportRulesPageParam reportRulesPageParam) {
        LambdaQueryWrapper<LabRptGroup> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LabRptGroup::getEnable, 1).eq(LabRptGroup::getDelFlag, 0);
        String businessType = reportRulesPageParam.getBusinessType();
        if (StringUtils.isNotBlank(businessType)) {
            queryWrapper.eq(LabRptGroup::getBusinessType, businessType);
        }
        return Result.succ(rptGroupService.getBaseMapper().selectList(queryWrapper));
    }

    @Override
    public Result getReportRulesByGroupId(String rptGroup) {
        MPJLambdaWrapper<PubReportRules> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper
                .selectAll(PubReportRules.class)
                .selectAs("pr", PubReport::getName, PubReportRules::getReportName)
                .leftJoin(PubReport.class, "pr", PubReport::getCode, PubReportRules::getReportCode)
                .eq(PubReportRules::getDelFlag, 0)
                .eq(PubReportRules::getRptGroup, rptGroup);
        List<PubReportRules> list = pubReportRulesMapper.selectList(lambdaQueryWrapper);
        return Result.succ(list);
    }

    @Override
    public Result findNotSelectDictItemByRules(String rulesId) {
        LambdaQueryWrapper<LabItemDict> itemDictwrapper = new LambdaQueryWrapper<>();
        itemDictwrapper.eq(LabItemDict::getDelFlag, 0);
        if (ToolsUtils.isNotEmpty(rulesId)) { //查所不在对应关系中的报告项目
            itemDictwrapper.notExists("SELECT 1 FROM LAB_RULES_VS_ITEMDICT t2 WHERE LAB_ITEM_DICT.id = t2.ITEM_DICT_ID AND t2. REPORT_RULES_ID = '" + rulesId + "' ");
        }
        List<LabItemDict> labItemDicts = itemDictMapper.selectList(itemDictwrapper);
        return Result.succ(1, "查询成功", labItemDicts);
    }

    /**
     * type 0规则二，1规则四
     */
    @Override
    public Result findDictItemByRules(String rulesId, String type) {
        if (ToolsUtils.isEmpty(rulesId)) {
            return Result.fail("异常---规则id为空！");
        }
        MPJLambdaWrapper<LabItemDict> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper.selectAll(LabItemDict.class).selectAs("rg", LabRulesVsItemdict::getId, LabItemDict::getRulesVSItemDictId).leftJoin(LabRulesVsItemdict.class, "rg", LabRulesVsItemdict::getItemDictId, LabItemDict::getId).eq(LabItemDict::getDelFlag, 0).eq(LabRulesVsItemdict::getReportRulesId, rulesId).eq(LabRulesVsItemdict::getType, type);

        List<LabItemDict> list = itemDictMapper.selectList(lambdaQueryWrapper);
        return Result.succ(list);
    }

    //规则二或四中，保存规则与项目的对应关系 ANIMAL_GP
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result saveRuleVsItemDict(LabRulesVsItemdictDto dto) {
        if (ToolsUtils.isEmpty(dto.getLabRulesVsItemdict())) {
            return Result.fail("入参异常！");
        }
        if (ToolsUtils.isEmpty(dto.getLabRulesVsItemdict().getRuleType())) {
            return Result.fail("规则标识未传入！");
        }
        String ruleType = dto.getLabRulesVsItemdict().getRuleType();
        if (ruleType.equals("2")) {
            if (ToolsUtils.isEmpty(dto.getLabRulesVsItemdict().getReportCode2())) {
                return Result.fail("务必选择规则2对应的报告模版！");
            }
        } else if (ruleType.equals("4")) {
            if (ToolsUtils.isEmpty(dto.getLabRulesVsItemdict().getReportCode2())) {
                return Result.fail("务必选择规则4对应的报告模版！");
            }
        }
        if (ToolsUtils.isEmpty(dto.getLabRulesVsItemdict().getReportGroupName())) {
            return Result.fail("报告单元未传入！");
        }
        String reportGroupName = dto.getLabRulesVsItemdict().getReportGroupName();
        SysUser sysUser = RedisUserManager.getUser();
        if (ToolsUtils.isEmpty(dto.getLabRulesVsItemdict().getReportRulesId())) {//判断报告规则id为空，则需要在规则表中插入一条数据
            PubReportRules pubReportRules = new PubReportRules();
            if (ruleType.equals("2")) {
                pubReportRules.setDescribe("报告单元【" + reportGroupName + "】 常规规则二");
                pubReportRules.setReportCode(dto.getLabRulesVsItemdict().getReportCode2());//规则二报告模版Id
                pubReportRules.setReportId(dto.getLabRulesVsItemdict().getReportId2());//报告模版Id
            } else if (ruleType.equals("4")) {
                pubReportRules.setDescribe("报告单元【" + reportGroupName + "】 常规规则四");
                pubReportRules.setReportCode(dto.getLabRulesVsItemdict().getReportCode4());//规则四报告模版Id
                pubReportRules.setReportId(dto.getLabRulesVsItemdict().getReportId4());//报告模版Id
            }
            pubReportRules.setType("0");
            pubReportRules.setIsUse("0");//默认启用
            pubReportRules.setOrgId(sysUser.getOrgId());
            pubReportRules.setRptGroup(dto.getLabRulesVsItemdict().getRptGroup());//报告单元
            pubReportRules.setRuleType(ruleType);//规则2或4
            pubReportRulesMapper.insert(pubReportRules);
            dto.getLabRulesVsItemdict().setReportRulesId(pubReportRules.getId());
        }
        if (ToolsUtils.isNotEmpty(sysUser)) {
            if (ToolsUtils.isNotEmpty(dto.getLabRulesVsItemdictList())) {
                for (LabRulesVsItemdict o : dto.getLabRulesVsItemdictList()) {
                    o.setOrgId(sysUser.getOrgId());
                }
            }
        }

        boolean isSave = rulesVsItemdictService.saveBatch(dto.getLabRulesVsItemdictList());
        if (isSave) {
            return Result.succ(1, "设置成功", dto.getLabRulesVsItemdict().getReportRulesId());
        } else {
            return Result.fail("设置失败！");
        }
    }

    @Override
    public Result saveRuleVsItemDictRuleFore(LabRulesVsItemdict labRulesVsItemdict) {
        if (ToolsUtils.isEmpty(labRulesVsItemdict)) {
            return Result.fail("入参异常！");
        }
        if (ToolsUtils.isEmpty(labRulesVsItemdict.getReportCode4())) {
            return Result.fail("务必选择对应的报告模版！");
        }
        SysUser sysUser = RedisUserManager.getUser();
        if (ToolsUtils.isEmpty(labRulesVsItemdict.getReportRulesId())) {//判断报告规则id为空，则需要在规则表中插入一条数据
            PubReportRules pubReportRules = new PubReportRules();
            pubReportRules.setDescribe("常规规则四");
            pubReportRules.setType("0");
            pubReportRules.setIsUse("0");//默认启用
            pubReportRules.setOrgId(sysUser.getOrgId());
            pubReportRules.setRptGroup(labRulesVsItemdict.getRptGroup());//报告单元
            pubReportRules.setReportCode(labRulesVsItemdict.getReportCode4());//报告模版Id
            pubReportRules.setReportId(labRulesVsItemdict.getReportId4());//报告模版Id
            pubReportRules.setRuleType("4");//规则4
            pubReportRulesMapper.insert(pubReportRules);
            labRulesVsItemdict.setReportRulesId(pubReportRules.getId());
            // System.out.println("pubReportRules.getId-----------------"+pubReportRules.getId());
        }
        if (ToolsUtils.isNotEmpty(sysUser)) {
            labRulesVsItemdict.setOrgId(sysUser.getOrgId());
        }
        labRulesVsItemdict.setType("1");//规则4
        int save = rulesVsItemdictMapper.insert(labRulesVsItemdict);
        if (save > 0) {
            return Result.succ(1, "", labRulesVsItemdict.getReportRulesId());
        } else {
            return Result.fail("添加失败！");
        }
    }

    @Override
    public Result deleleRuleVsItemDict(DeleteParam param) {
        if (ToolsUtils.isEmpty(param)) {
            return Result.fail("入参异常！");
        }
        int i = rulesVsItemdictMapper.deleteById(param.getId());
        if (i > 0) {
            return Result.succ(1, "移除成功", null);
        } else {
            return Result.fail("移除失败！");
        }
    }

    @Override
    public Result updateReportRuleByRuleId1(LabRulesVsItemdict labRulesVsItemdict) {
        if (ToolsUtils.isEmpty(labRulesVsItemdict)) {
            return Result.fail("入参异常！");
        }
        SysUser sysUser = RedisUserManager.getUser();
        int isOk = 0;
        String ruleOneId = "";
        if (ToolsUtils.isEmpty(labRulesVsItemdict.getReportRulesId())) {//执行新增
            //若新增时，先删除原有数据
            this.prrRemoveDuplicate(labRulesVsItemdict.getRptGroup(), "1", "-1");
            PubReportRules pubReportRules = new PubReportRules();
            pubReportRules.setDescribe("报告单元【" + labRulesVsItemdict.getReportGroupName() + "】常规规则一");
            pubReportRules.setType("0");
            pubReportRules.setIsUse("0");//默认启用
            pubReportRules.setOrgId(sysUser.getOrgId());
            pubReportRules.setRptGroup(labRulesVsItemdict.getRptGroup());//报告单元
            pubReportRules.setReportCode(labRulesVsItemdict.getReportCode1());//报告模版Id
            pubReportRules.setReportId(labRulesVsItemdict.getReportId1());//报告模版Id
            pubReportRules.setRuleType("1");//规则1
            isOk = pubReportRulesMapper.insert(pubReportRules);
            ruleOneId = pubReportRules.getId();
        } else {//执行修改模版信息
            PubReportRules selectPubReportRules = this.prrRemoveDuplicate(labRulesVsItemdict.getRptGroup(), "1", labRulesVsItemdict.getReportRulesId());
            selectPubReportRules.setReportCode(labRulesVsItemdict.getReportCode1());
            selectPubReportRules.setReportId(labRulesVsItemdict.getReportId1());
//            LambdaUpdateWrapper<PubReportRules> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
//            lambdaUpdateWrapper.set(PubReportRules::getReportCode, labRulesVsItemdict.getReportCode1())
//                    .set(PubReportRules::getReportId, labRulesVsItemdict.getReportId1())
//                    .eq(PubReportRules::getId, labRulesVsItemdict.getReportRulesId());
//            isOk = pubReportRulesMapper.update(null, lambdaUpdateWrapper);
//            ruleOneId = labRulesVsItemdict.getReportRulesId();
            isOk = this.baseMapper.updateById(selectPubReportRules);
            ruleOneId = selectPubReportRules.getId();
        }
        if (isOk > 0) {
            return Result.succ(1, "执行成功", ruleOneId);
        } else {
            return Result.fail("执行失败！");
        }
    }

    //处理查询到的模板，仅保留一个模板
    private PubReportRules prrRemoveDuplicate(String rptGroup, String ruleType, String rrid) {
        List<PubReportRules> list = selectReportRule(rptGroup, ruleType);
        PubReportRules pubReportRules = null;
        for (PubReportRules itme : list) {
            if (itme.getId().equals(rrid)) {
                pubReportRules = itme;
            } else {
                LambdaUpdateWrapper<PubReportRules> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                lambdaUpdateWrapper.set(PubReportRules::getDelFlag, 1)
                        .eq(PubReportRules::getId, itme.getId());
                this.baseMapper.update(null, lambdaUpdateWrapper);
            }
        }
        return pubReportRules;
    }

    //查询规则已设置的模板
    public List<PubReportRules> selectReportRule(String rptGroup, String ruleType) {
        MPJLambdaWrapper<PubReportRules> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper
                .selectAll(PubReportRules.class)
                .selectAs("pr", PubReport::getName, PubReportRules::getReportName)
                .leftJoin(PubReport.class, "pr", PubReport::getCode, PubReportRules::getReportCode)
                .eq(PubReportRules::getDelFlag, 0)
                .eq(PubReportRules::getRptGroup, rptGroup)
                .eq(PubReportRules::getRuleType, ruleType);
        List<PubReportRules> list = this.baseMapper.selectList(lambdaQueryWrapper);
        return list;
    }

    @Override
    public Result updateReportRuleByRuleId2(LabRulesVsItemdict labRulesVsItemdict) {
        if (ToolsUtils.isEmpty(labRulesVsItemdict)) {
            return Result.fail("入参异常！");
        }
        SysUser sysUser = RedisUserManager.getUser();
        int isOk = 0;
        String ruleTwoId = "";
        if (ToolsUtils.isEmpty(labRulesVsItemdict.getReportRulesId())) {//执行新增
            this.prrRemoveDuplicate(labRulesVsItemdict.getRptGroup(), "2", "-1");
            PubReportRules pubReportRules = new PubReportRules();
            pubReportRules.setDescribe("报告单元【" + labRulesVsItemdict.getReportGroupName() + "】常规规则二");
            pubReportRules.setType("0");
            pubReportRules.setIsUse("0");//默认启用
            pubReportRules.setOrgId(sysUser.getOrgId());
            pubReportRules.setRptGroup(labRulesVsItemdict.getRptGroup());//报告单元
            pubReportRules.setReportCode(labRulesVsItemdict.getReportCode2());//报告模版Id
            pubReportRules.setReportId(labRulesVsItemdict.getReportId2());//报告模版Id
            pubReportRules.setRuleType("2");//规则2
            isOk = pubReportRulesMapper.insert(pubReportRules);
            ruleTwoId = pubReportRules.getId();
        } else {//执行修改模版信息
            PubReportRules selectPubReportRules = this.prrRemoveDuplicate(labRulesVsItemdict.getRptGroup(), "2", labRulesVsItemdict.getReportRulesId());
            selectPubReportRules.setReportCode(labRulesVsItemdict.getReportCode2());
            selectPubReportRules.setReportId(labRulesVsItemdict.getReportId2());
            /*LambdaUpdateWrapper<PubReportRules> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.set(PubReportRules::getReportCode, labRulesVsItemdict.getReportCode2())
                    .set(PubReportRules::getReportId, labRulesVsItemdict.getReportId2())
                    .eq(PubReportRules::getId, labRulesVsItemdict.getReportRulesId());
            isOk = pubReportRulesMapper.update(null, lambdaUpdateWrapper);*/
            isOk = this.baseMapper.updateById(selectPubReportRules);
            ruleTwoId = selectPubReportRules.getId();
        }
        if (isOk > 0) {
            return Result.succ(1, "执行成功", ruleTwoId);
        } else {
            return Result.fail("执行失败！");
        }
    }

    @Override
    public Result updateReportRuleByRuleId3(LabRulesVsItemdict labRulesVsItemdict) {
        if (ToolsUtils.isEmpty(labRulesVsItemdict)) {
            return Result.fail("入参异常！");
        }
        SysUser sysUser = RedisUserManager.getUser();
        int isOk = 0;
        String ruleThreeId = "";
        if (ToolsUtils.isEmpty(labRulesVsItemdict.getReportRulesId())) {//执行新增
            this.prrRemoveDuplicate(labRulesVsItemdict.getRptGroup(), "3", "-1");
            PubReportRules pubReportRules = new PubReportRules();
            pubReportRules.setDescribe("报告单元【" + labRulesVsItemdict.getReportGroupName() + "】常规规则三");
            pubReportRules.setType("0");
            pubReportRules.setIsUse("0");//默认启用
            pubReportRules.setOrgId(sysUser.getOrgId());
            pubReportRules.setRptGroup(labRulesVsItemdict.getRptGroup());//报告单元
            pubReportRules.setReportCode(labRulesVsItemdict.getReportCode3());//报告模版Id
            pubReportRules.setReportId(labRulesVsItemdict.getReportId3());//报告模版Id
            pubReportRules.setRuleType("3");//规则3
            isOk = pubReportRulesMapper.insert(pubReportRules);
            ruleThreeId = pubReportRules.getId();
        } else {//执行修改模版信息
            PubReportRules selectPubReportRules = this.prrRemoveDuplicate(labRulesVsItemdict.getRptGroup(), "3", labRulesVsItemdict.getReportRulesId());
            selectPubReportRules.setReportCode(labRulesVsItemdict.getReportCode3());
            selectPubReportRules.setReportId(labRulesVsItemdict.getReportId3());
            /*LambdaUpdateWrapper<PubReportRules> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.set(PubReportRules::getReportCode, labRulesVsItemdict.getReportCode3())
                    .set(PubReportRules::getReportId, labRulesVsItemdict.getReportId3())
                    .eq(PubReportRules::getId, labRulesVsItemdict.getReportRulesId());
            isOk = pubReportRulesMapper.update(null, lambdaUpdateWrapper);*/
            isOk = this.baseMapper.updateById(selectPubReportRules);
            ruleThreeId = selectPubReportRules.getId();
        }
        if (isOk > 0) {
            return Result.succ(1, "执行成功", ruleThreeId);
        } else {
            return Result.fail("执行失败！");
        }
    }

    @Override
    public Result updateReportRuleByRuleId4(LabRulesVsItemdict labRulesVsItemdict) {
        if (ToolsUtils.isEmpty(labRulesVsItemdict)) {
            return Result.fail("入参异常！");
        }
        SysUser sysUser = RedisUserManager.getUser();
        int isOk = 0;
        String ruleForeId = "";
        if (ToolsUtils.isEmpty(labRulesVsItemdict.getReportRulesId())) {//执行新增
            this.prrRemoveDuplicate(labRulesVsItemdict.getRptGroup(), "4", "-1");
            PubReportRules pubReportRules = new PubReportRules();
            pubReportRules.setDescribe("报告单元【" + labRulesVsItemdict.getReportGroupName() + "】常规规则四");
            pubReportRules.setType("0");
            pubReportRules.setIsUse("0");//默认启用
            pubReportRules.setOrgId(sysUser.getOrgId());
            pubReportRules.setRptGroup(labRulesVsItemdict.getRptGroup());//报告单元
            pubReportRules.setReportCode(labRulesVsItemdict.getReportCode4());//报告模版Id
            pubReportRules.setReportId(labRulesVsItemdict.getReportId4());//报告模版Id
            pubReportRules.setRuleType("4");//规则4
            pubReportRules.setIsSplit(labRulesVsItemdict.getIsSplit());/*是否拆分报告*/
            isOk = pubReportRulesMapper.insert(pubReportRules);
            ruleForeId = pubReportRules.getId();
        } else {//执行修改模版信息
            PubReportRules selectPubReportRules = this.prrRemoveDuplicate(labRulesVsItemdict.getRptGroup(), "4", labRulesVsItemdict.getReportRulesId());
            selectPubReportRules.setReportCode(labRulesVsItemdict.getReportCode4());
            selectPubReportRules.setReportId(labRulesVsItemdict.getReportId4());
            selectPubReportRules.setIsSplit(labRulesVsItemdict.getIsSplit());
            /*LambdaUpdateWrapper<PubReportRules> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.set(PubReportRules::getReportCode, labRulesVsItemdict.getReportCode4())
                    .set(PubReportRules::getReportId, labRulesVsItemdict.getReportId4())
                    .set(PubReportRules::getIsSplit, labRulesVsItemdict.getIsSplit())
                    .eq(PubReportRules::getId, labRulesVsItemdict.getReportRulesId());
            isOk = pubReportRulesMapper.update(null, lambdaUpdateWrapper);*/
            isOk = this.baseMapper.updateById(selectPubReportRules);
            ruleForeId = selectPubReportRules.getId();
        }
        if (isOk > 0) {
            return Result.succ(1, "执行成功", ruleForeId);
        } else {
            return Result.fail("执行失败！");
        }
    }

    @Override
    public Result rulesSave(LabRulesVsItemdict labRulesVsItemdict) {
        if (ToolsUtils.isEmpty(labRulesVsItemdict)) {
            return Result.fail("入参异常！");
        }
        SysUser sysUser = RedisUserManager.getUser();
        String msg = "";
        int isOk = 0;
        //修改规则二中的 项目超过  项时使用 或包含一下项目使用
        if (ToolsUtils.isNotEmpty(labRulesVsItemdict.getRuleTwoId())) {
            LambdaUpdateWrapper<PubReportRules> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.set(PubReportRules::getRules, labRulesVsItemdict.getRules2())
                    .eq(PubReportRules::getId, labRulesVsItemdict.getRuleTwoId());
            isOk = pubReportRulesMapper.update(null, lambdaUpdateWrapper);
            if (isOk < 0) {
                msg = "规则存储异常--1";
                return Result.fail(msg);
            }
        }
        //处理规则三中的数据
        if (ToolsUtils.isNotEmpty(labRulesVsItemdict.getRuleThreeId())) {//执行修改
            LambdaUpdateWrapper<PubReportRules> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.set(PubReportRules::getRules, labRulesVsItemdict.getRules3())
                    .eq(PubReportRules::getId, labRulesVsItemdict.getRuleThreeId());
            isOk = pubReportRulesMapper.update(null, lambdaUpdateWrapper);
            if (isOk < 0) {
                msg = "规则存储异常--2";
                return Result.fail(msg);
            }
        }

        return Result.succ(1, "执行成功", isOk);
    }

    @Override
    public Result getReportRuleListByGroupId(ReportRulesPageParam reportRulesPageParam) {
        MPJLambdaWrapper<PubReportRules> lambdaQueryWrapper = new MPJLambdaWrapper();
        lambdaQueryWrapper.selectAll(PubReportRules.class).selectAs(PubReport::getName, PubReportRules::getReportName).leftJoin(PubReport.class, PubReport::getCode, PubReportRules::getReportCode).eq(PubReportRules::getDelFlag, 0).eq(PubReportRules::getRptGroup, reportRulesPageParam.getRptGroup()).eq(PubReportRules::getType, "1");

        if (!StringUtils.isEmpty(reportRulesPageParam.getKeywords())) {
            lambdaQueryWrapper.like(PubReportRules::getReportName, reportRulesPageParam.getKeywords());
        }
        lambdaQueryWrapper.orderByAsc(PubReportRules::getPriorityLevel);
        List<PubReportRules> list = pubReportRulesMapper.selectList(lambdaQueryWrapper);
        return Result.succ(list);
    }

    @Override
    public Result addReportRuleList(PubReportRules reportRules) {
        if (ToolsUtils.isEmpty(reportRules)) {
            return Result.fail("入参异常");
        }
        SysUser sysUser = RedisUserManager.getUser();
        reportRules.setOrgId(sysUser.getOrgId());
        reportRules.setIsUse("1");
        if (ToolsUtils.isNotEmpty(reportRules.getDescribe())) {
            String factorDescribe = reportRules.getDescribe();
            reportRules.setDescribe(factorDescribe + " )");
        }
        boolean save = this.save(reportRules);
        if (save) {
            return Result.succ(1, "添加成功！", null);
        } else {
            return Result.fail("添加失败！");
        }
    }

    @Override
    public Result editReportRuleList(PubReportRules reportRules) {
        if (ToolsUtils.isNotEmpty(reportRules.getDescribe())) {
            String factorDescribe = reportRules.getDescribe();
            reportRules.setDescribe(factorDescribe + " )");
        }
        if (ToolsUtils.isEmpty(reportRules)) {
            return Result.fail("入参异常");
        }
        rulesExistService.remove(new LambdaQueryWrapper<PubPeportRulesExist>().eq(PubPeportRulesExist::getRuleId, reportRules.getId()));
        if (CollectionUtil.isNotEmpty(reportRules.getReferDataList())) {
            List<PubPeportRulesExist> list = new ArrayList<>();
            for (PubRuleDataDto pubRuleDataDto : reportRules.getReferDataList()) {
                if ((pubRuleDataDto.getOperation().equals("exists") || pubRuleDataDto.getOperation().equals("notexists")) && pubRuleDataDto.getValuearr().length > 0) {
                    for (String value : pubRuleDataDto.getValuearr()) {
                        PubPeportRulesExist pubPeportRulesExist = new PubPeportRulesExist();
                        pubPeportRulesExist.setRuleId(reportRules.getId());
                        pubPeportRulesExist.setFieldCode(pubRuleDataDto.getCode());
                        pubPeportRulesExist.setFieldValue(value);
                        list.add(pubPeportRulesExist);
                    }
                }
            }
            rulesExistService.saveBatch(list);
        }
        boolean save = this.updateById(reportRules);
        if (save) {
            return Result.succ(1, "修改成功！", null);
        } else {
            return Result.fail("修改失败！");
        }
    }

    @Override
    public Result deleteReportRuleList(ReportRuleDto deleteParam) {
        List<PubReportRules> reportRulesList = deleteParam.getReportRulesList();

        List<String> ids = reportRulesList.stream().map(PubReportRules::getId).collect(Collectors.toList());

        rulesExistService.remove(new LambdaQueryWrapper<PubPeportRulesExist>().in(PubPeportRulesExist::getRuleId, ids));
        boolean b = this.removeByIds(ids);
        if (b) {
            return Result.succ(1, "删除成功", null);
        } else {
            return Result.fail(400, "删除失败", "");
        }
    }

    /*删除规则*/
    @Override
    public Result deleteReportRule(String Id) {
        if (ToolsUtils.isEmpty(Id)) {
            return Result.fail("Id为空");
        }
        LambdaQueryWrapper<PubReportRules> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(PubReportRules::getId, Id);
        boolean i = this.remove(lambdaQueryWrapper);
        return i ? Result.succ(1, "删除成功", "") : Result.fail(0, "删除失败", "");
    }

    @Override
    public Result getReportGroupPoct(ReportRulesPageParam reportRulesPageParam) {
        LambdaQueryWrapper<LabRptGroup> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LabRptGroup::getEnable, 1).eq(LabRptGroup::getDelFlag, 0);
        String businessType = reportRulesPageParam.getBusinessType();
        if (StringUtils.isNotBlank(businessType)) {
            queryWrapper.eq(LabRptGroup::getBusinessType, businessType);
        }
        queryWrapper.eq(LabRptGroup::getPoct,"1");
        return Result.succ(rptGroupService.getBaseMapper().selectList(queryWrapper));
    }

}